import { ScrollView, View } from "@tarojs/components";

import HeaderSearch from "@/components/HeaderSearch/index";
import Header from "@/components/Header/index";
import Footer from "@/components/Footer/index";
import GoodsTitle from "@/components/GoodsTitle/index";
import { useEffect, useRef, useState } from "react";
import {
  Button,
  Image,
  Popup,
  Toast,
  Dialog,
  Pagination,
  Empty,
  Tabs,
  Radio,
  Form,
  Cell,
  Input,
  Uploader,
} from "@taroify/core";
import { requestPOST } from "@/request";
import { PhotoFail } from "@taroify/icons";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import StyleModule from "./index.module.scss";
import Taro from "@tarojs/taro";

export default function Index() {
  const businessId = useSelector(
    (state: RootState) => state.business.businessId
  );

  const [list, setList] = useState<any>([]);
  const [current, setCurrent] = useState(1);
  const [count, setCount] = useState(0);
  const [current1, setCurrent1] = useState(1);
  const [count1, setCount1] = useState(0);
  const [open, setOpen] = useState(false);
  const [open1, setOpen1] = useState(false);
  const [value, setValue] = useState<any>("");
  const [form, setForm] = useState({
    id: "",
    status: 0,
    toUser: "",
    commodityName: "",
    specifications: "",
    unitPrice: "",
    quantity: "",
    businessEmail: "",
    totalPrice: "",
    collectionType: 1,
    collectionQrcode: "",
    beneficiaryName: "",
    beneficiaryAddress: "",
    beneficiaryAccNo: "",
    addressOfBank: "",
    swiftCode: "",
    postCode: "",
    beneficiaryBank: "",
    tel: "",
    customDefinition: "",
  });
  const [orderList, setOrederList] = useState<any>([]);
  const [orderVos, setOrderVos] = useState<any>([]);
  const [files, setFiles] = useState<Uploader.File[]>([]);
  const [curInfo, setCurInfo] = useState<any>({});

  const getList = (page?: number) => {
    requestPOST(`shop/shopEnquiriesList`, {
      businessId: businessId,
      status: null,
      pageNum: page || current,
      pageSize: 5,
    }).then((res: any) => {
      setCount(Math.ceil(res.total / 5));
      setList([...res.vos]);
    });
  };

  const editList = (item) => {
    setOpen(true);

    if (item.orderVos && item.orderVos.length) {
      setCount1(item.orderVos.length);
      setOrderVos([...item.orderVos]);
      setOrederList([item.orderVos[0]]);
    }
  };
  const handleChange1 = (page) => {
    setCurrent1(page);
    orderVos[page] && setOrederList(orderVos[page]);
  };

  const delList = (item) => {
    setForm({ ...form, id: item.id });
    setCurInfo(item);
    setOpen1(true);
  };

  const orderFun = (id) => {
    if (value !== 3 && value !== 1 && value !== 2) {
      return Toast.open({ type: "fail", message: "请选择修改状态" });
    }
    Dialog.confirm({
      title: "提示",
      message: "您确定要修改吗？",
      onConfirm() {
        requestPOST(`shop/modifyEnquiriesOrder/${id}/${value}`).then(() => {
          Toast.open({ type: "success", message: "修改成功" });
          setOpen(false);
          getList();
        });
      },
    });
  };

  const handleChange = (page) => {
    setCurrent(page);
    getList(page);
  };

  const onUpload = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
    }).then(({ tempFiles, tempFilePaths }) => {
      Taro.uploadFile({
        url: process.env.TARO_APP_API + "/other/upload",
        filePath: tempFilePaths[0],
        name: "file",
        success(res) {
          setFiles([
            ...tempFiles.map(({ path, type, originalFileObj }) => ({
              type,
              url: path,
              name: originalFileObj?.name,
            })),
          ]);
          const { relativeUrl } = JSON.parse(res.data).data;
          setForm({
            ...form,
            collectionQrcode: relativeUrl,
          });
          Toast.open({ type: "success", message: "上传成功" });
        },
        fail() {
          Toast.open({ type: "fail", message: "upload error" });
        },
      });
    });
  };

  const closeHandle = () => {
    setOpen1(false);
    setForm({
      id: "",
      status: 0,
      toUser: "",
      commodityName: "",
      specifications: "",
      unitPrice: "",
      quantity: "",
      businessEmail: "",
      totalPrice: "",
      collectionType: 1,
      collectionQrcode: "",
      beneficiaryName: "",
      beneficiaryAddress: "",
      beneficiaryAccNo: "",
      addressOfBank: "",
      swiftCode: "",
      postCode: "",
      beneficiaryBank: "",
      tel: "",
      customDefinition: "",
    });
    formRef.current?.reset();
  };

  const onSubmit = () => {
    requestPOST("shop/shopEnquiriesStatus", { ...form }).then(() => {
      Toast.open({ type: "success", message: "审核成功" });
      closeHandle();
      getList();
    });
  };

  useEffect(() => {
    getList();
  }, []);

  const formRef = useRef<any>();

  return (
    <View className="taroBox">
      <HeaderSearch />
      <Header />
      <View>
        <GoodsTitle title="询盘中心" isMore={false} />
        <View
          style={{
            display: "flex",
            flexDirection: "column",
            gap: "20px",
            padding: "14px",
          }}
        >
          {!list.length && (
            <Empty>
              <Empty.Image />
              <Empty.Description>暂无数据</Empty.Description>
            </Empty>
          )}
          {list.map((item) => (
            <View
              key={item.id}
              style={{
                padding: "10px",
                boxShadow: "0 0 .3125rem 0 hsla(0, 0%, 49%, 0.45)",
                fontSize: "14px",
              }}
            >
              <View
                style={{
                  display: "flex",
                  gap: "10px",
                }}
              >
                <View style={{ width: "102px" }}>
                  <Image
                    src={
                      item.image
                        ? process.env.TARO_APP_API + item.image
                        : "error"
                    }
                    width={102}
                    height="100%"
                    mode="aspectFill"
                    fallback={<PhotoFail />}
                  />
                </View>
                <View
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    gap: "5px",
                  }}
                >
                  <View className={StyleModule.name}>{item.commodityName}</View>
                  <View className={StyleModule.name1}>
                    商品分类：{item.categoryName}
                  </View>
                </View>
              </View>
              <View style={{ marginTop: "10px" }}>
                商品规格：{item.specifications}
              </View>
              <View>购买数量：{item.quantity}</View>
              <View>现价：{item.presentPrice}</View>
              <View>邮箱：{item.email}</View>
              <View>备注：{item.message}</View>
              <View>审核状态：{item.status ? "审核通过" : "审核中"}</View>
              <View
                style={{
                  display: "flex",
                  gap: "20px",
                  alignItems: "center",
                  marginTop: "10px",
                }}
              >
                {item.status ? (
                  <Button
                    color="primary"
                    size="small"
                    variant="outlined"
                    onClick={() => editList(item)}
                  >
                    查看订单
                  </Button>
                ) : (
                  <Button
                    color="primary"
                    size="small"
                    variant="outlined"
                    onClick={() => delList(item)}
                  >
                    审核
                  </Button>
                )}
              </View>
            </View>
          ))}
        </View>
        <View style={{ marginBlock: "1.25rem", padding: "0 .875rem" }}>
          <Pagination
            current={current}
            siblingCount={1}
            count={count}
            onChange={(page) => handleChange(page)}
          >
            <Pagination.Item type="start-ellipsis" />
            <Pagination.Item type="end-ellipsis" />
          </Pagination>
        </View>
      </View>
      <Footer />

      <Popup
        open={open}
        placement="center"
        style={{ height: "auto" }}
        rounded
        onClose={() => setOpen(false)}
        lock={false}
      >
        <ScrollView style={{ maxHeight: "90vh" }} scrollY>
          <View style={{ width: "90vw", padding: "14px", fontSize: "14px" }}>
            {!orderList.length && (
              <Empty>
                <Empty.Image />
                <Empty.Description>暂无数据</Empty.Description>
              </Empty>
            )}
            {orderList.map((item) => (
              <View
                style={{
                  padding: "14px 0",
                  display: "flex",
                  gap: "5px",
                  flexDirection: "column",
                }}
              >
                <View>商品名称：{item.commodityName}</View>
                <View>商品规格：{item.specifications}</View>
                <View
                  style={{ display: "flex", alignItems: "center", gap: "20px" }}
                >
                  <View>购买数量：{item.quantity}</View>
                  <View>单价：{item.unitPrice}</View>
                </View>
                <View
                  style={{ display: "flex", alignItems: "center", gap: "20px" }}
                >
                  <View>支付状态：{item.status ? "已支付" : "未支付"}</View>
                  <View>总价：{item.totalPrice}</View>
                </View>
                <View>回件商家邮箱：{item.businessEmail}</View>
                <View
                  style={{
                    borderBottom: "1px solid #efefef",
                    paddingBottom: "10px",
                  }}
                >
                  是否发送邮箱：{item.isEmail ? "已发送" : "未发送"}
                </View>
                <Tabs>
                  {item.collectionQrcode ? (
                    <Tabs.TabPane title="二维码">
                      <View
                        style={{
                          marginTop: "10px",
                          display: "flex",
                          justifyContent: "center",
                        }}
                      >
                        <Image
                          src={process.env.TARO_APP_API + item.collectionQrcode}
                          width={200}
                          height={200}
                          mode="aspectFill"
                        />
                      </View>
                    </Tabs.TabPane>
                  ) : (
                    <Tabs.TabPane title="银行卡">
                      <View
                        style={{
                          marginTop: "10px",
                          display: "flex",
                          gap: "5px",
                          flexDirection: "column",
                        }}
                      >
                        <View>受益人姓名：{item.beneficiaryName}</View>
                        <View>受益人地址：{item.beneficiaryAddress}</View>
                        <View>受益人账号：{item.beneficiaryAccNo}</View>
                        <View>银行地址：{item.addressOfBank}</View>
                        <View>SWIFT码：{item.swiftCode}</View>
                        <View>邮政编码：{item.postCode}</View>
                        <View>电话：{item.tel}</View>
                      </View>
                    </Tabs.TabPane>
                  )}
                </Tabs>
                <View
                  style={{ display: "flex", alignItems: "center", gap: "5px" }}
                >
                  <View>状态：审核通过</View>
                </View>
              </View>
            ))}

            <View style={{ marginBlock: "1.25rem", padding: "0 .875rem" }}>
              <Pagination
                current={current1}
                siblingCount={1}
                count={count1}
                onChange={(page) => handleChange1(page)}
              >
                <Pagination.Item type="start-ellipsis" />
                <Pagination.Item type="end-ellipsis" />
              </Pagination>
            </View>
          </View>
        </ScrollView>
      </Popup>

      <Popup
        open={open1}
        placement="center"
        style={{ height: "auto" }}
        rounded
        onClose={() => setOpen1(false)}
        lock={false}
      >
        <ScrollView style={{ maxHeight: "90vh" }} scrollY>
          <View style={{ width: "90vw", padding: "14px 0" }}>
            <Form ref={formRef} defaultValues={form} onSubmit={() => onSubmit()}>
              <Cell.Group inset>
                <View
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    gap: "4px",
                    fontSize: "14px",
                    marginBottom: "20px",
                  }}
                >
                  <View style={{ fontSize: "16px", marginBottom: "10px" }}>
                    询盘商品详细信息
                  </View>
                  <View style={{ display: "flex", gap: "10px" }}>
                    <View style={{ width: "100px" }}>
                      <Image
                        src={
                          curInfo.image
                            ? process.env.TARO_APP_API + curInfo.image
                            : "error"
                        }
                        width={100}
                        height="100%"
                        mode="aspectFill"
                        fallback={<PhotoFail />}
                      />
                    </View>
                    <View>
                      <View
                        style={{
                          fontSize: "16px",
                          display: "-webkit-box",
                          WebkitBoxOrient: "vertical",
                          WebkitLineClamp: "2",
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          wordBreak: "break-all",
                        }}
                      >
                        {curInfo.commodityName}
                      </View>
                      <View
                        style={{
                          color: "#555",
                          textOverflow: "ellipsis",
                          overflow: "hidden",
                          whiteSpace: "nowrap",
                        }}
                      >
                        {curInfo.categoryName}
                      </View>
                    </View>
                  </View>
                  <View>规格：{curInfo.specifications}</View>
                  <View>购买数量：{curInfo.quantity}</View>
                  <View>消费者收件箱：{curInfo.email}</View>
                  <View>备注：{curInfo.message}</View>
                  <View>
                    审核状态：{curInfo.status ? "审核通过" : "审核中"}
                  </View>
                </View>
                <View style={{ fontSize: "16px", marginBottom: "10px" }}>
                  确认信息
                </View>
                <Form.Item
                  name="status"
                  rules={[{ required: true, message: "请选择状态" }]}
                >
                  <Form.Label>状态</Form.Label>
                  <Form.Control>
                    <Radio.Group
                      value={form.status}
                      onChange={(value) => setForm({ ...form, status: value })}
                    >
                      <Radio name={1}>通过</Radio>
                      <Radio name={2}>未通过</Radio>
                    </Radio.Group>
                  </Form.Control>
                </Form.Item>
                {form.status === 1 && (
                  <View>
                    <Form.Item name="toUser">
                      <Form.Label>收件人邮箱</Form.Label>
                      <Form.Control>
                        <Input
                          placeholder="收件人邮箱"
                          onChange={(e) =>
                            setForm({ ...form, toUser: e.detail.value })
                          }
                        />
                      </Form.Control>
                    </Form.Item>
                    <Form.Item name="commodityName">
                      <Form.Label>商品名称</Form.Label>
                      <Form.Control>
                        <Input
                          placeholder="商品名称"
                          onChange={(e) =>
                            setForm({ ...form, commodityName: e.detail.value })
                          }
                        />
                      </Form.Control>
                    </Form.Item>
                    <Form.Item name="specifications">
                      <Form.Label>商品规格</Form.Label>
                      <Form.Control>
                        <Input
                          placeholder="商品规格"
                          onChange={(e) =>
                            setForm({ ...form, specifications: e.detail.value })
                          }
                        />
                      </Form.Control>
                    </Form.Item>
                    <Form.Item name="unitPrice">
                      <Form.Label>单价</Form.Label>
                      <Form.Control>
                        <Input
                          placeholder="单价"
                          onChange={(e) =>
                            setForm({ ...form, unitPrice: e.detail.value })
                          }
                        />
                      </Form.Control>
                    </Form.Item>
                    <Form.Item name="quantity">
                      <Form.Label>购买数量</Form.Label>
                      <Form.Control>
                        <Input
                          placeholder="购买数量"
                          onChange={(e) =>
                            setForm({ ...form, quantity: e.detail.value })
                          }
                        />
                      </Form.Control>
                    </Form.Item>
                    <Form.Item name="businessEmail">
                      <Form.Label>回件商家邮箱</Form.Label>
                      <Form.Control>
                        <Input
                          placeholder="回件商家邮箱"
                          onChange={(e) =>
                            setForm({ ...form, businessEmail: e.detail.value })
                          }
                        />
                      </Form.Control>
                    </Form.Item>
                    <Form.Item name="totalPrice">
                      <Form.Label>总价</Form.Label>
                      <Form.Control>
                        <Input
                          placeholder="总价"
                          onChange={(e) =>
                            setForm({ ...form, totalPrice: e.detail.value })
                          }
                        />
                      </Form.Control>
                    </Form.Item>
                    <Form.Item name="collectionType">
                      <Form.Label>收款方式</Form.Label>
                      <Form.Control>
                        <Radio.Group
                          onChange={(value) =>
                            setForm({ ...form, collectionType: value })
                          }
                        >
                          <Radio name={1}>二维码</Radio>
                          <Radio name={2}>银行卡</Radio>
                        </Radio.Group>
                      </Form.Control>
                    </Form.Item>
                    {form.collectionType === 1 ? (
                      <Form.Item name="email">
                        <Form.Label>收款码地址</Form.Label>
                        <Form.Control>
                          <Uploader
                            value={files}
                            onUpload={onUpload}
                            onChange={(value) => {
                              setFiles(value);
                              setForm({ ...form, collectionQrcode: "" });
                            }}
                          ></Uploader>
                        </Form.Control>
                      </Form.Item>
                    ) : (
                      <View>
                        <Form.Item name="beneficiaryName">
                          <Form.Label>受益人姓名</Form.Label>
                          <Form.Control>
                            <Input
                              placeholder="受益人姓名"
                              onChange={(e) =>
                                setForm({
                                  ...form,
                                  beneficiaryName: e.detail.value,
                                })
                              }
                            />
                          </Form.Control>
                        </Form.Item>
                        <Form.Item name="beneficiaryAddress">
                          <Form.Label>受益人地址</Form.Label>
                          <Form.Control>
                            <Input
                              placeholder="受益人地址"
                              onChange={(e) =>
                                setForm({
                                  ...form,
                                  beneficiaryAddress: e.detail.value,
                                })
                              }
                            />
                          </Form.Control>
                        </Form.Item>
                        <Form.Item name="beneficiaryAccNo">
                          <Form.Label>受益人账号</Form.Label>
                          <Form.Control>
                            <Input
                              placeholder="受益人账号"
                              onChange={(e) =>
                                setForm({
                                  ...form,
                                  beneficiaryAccNo: e.detail.value,
                                })
                              }
                            />
                          </Form.Control>
                        </Form.Item>
                        <Form.Item name="addressOfBank">
                          <Form.Label>银行地址</Form.Label>
                          <Form.Control>
                            <Input
                              placeholder="银行地址"
                              onChange={(e) =>
                                setForm({
                                  ...form,
                                  addressOfBank: e.detail.value,
                                })
                              }
                            />
                          </Form.Control>
                        </Form.Item>
                        <Form.Item name="swiftCode">
                          <Form.Label>SWIFT码</Form.Label>
                          <Form.Control>
                            <Input
                              placeholder="SWIFT码"
                              onChange={(e) =>
                                setForm({ ...form, swiftCode: e.detail.value })
                              }
                            />
                          </Form.Control>
                        </Form.Item>
                        <Form.Item name="postCode">
                          <Form.Label>邮政编码</Form.Label>
                          <Form.Control>
                            <Input
                              placeholder="邮政编码"
                              onChange={(e) =>
                                setForm({ ...form, postCode: e.detail.value })
                              }
                            />
                          </Form.Control>
                        </Form.Item>
                        <Form.Item name="beneficiaryBank">
                          <Form.Label>受益人银行</Form.Label>
                          <Form.Control>
                            <Input
                              placeholder="受益人银行"
                              onChange={(e) =>
                                setForm({
                                  ...form,
                                  beneficiaryBank: e.detail.value,
                                })
                              }
                            />
                          </Form.Control>
                        </Form.Item>
                        <Form.Item name="tel">
                          <Form.Label>电话</Form.Label>
                          <Form.Control>
                            <Input
                              placeholder="电话"
                              onChange={(e) =>
                                setForm({ ...form, tel: e.detail.value })
                              }
                            />
                          </Form.Control>
                        </Form.Item>
                        <Form.Item name="customDefinition">
                          <Form.Label>自定义字段</Form.Label>
                          <Form.Control>
                            <Input
                              placeholder="自定义字段"
                              onChange={(e) =>
                                setForm({
                                  ...form,
                                  customDefinition: e.detail.value,
                                })
                              }
                            />
                          </Form.Control>
                        </Form.Item>
                      </View>
                    )}
                  </View>
                )}
              </Cell.Group>
              <View
                style={{
                  margin: "1rem",
                  display: "flex",
                  alignItems: "center",
                  gap: "30px",
                }}
              >
                <Button
                  shape="round"
                  block
                  color="primary"
                  variant="outlined"
                  onClick={() => closeHandle()}
                >
                  取消
                </Button>
                <Button shape="round" block color="primary" formType="submit">
                  审核
                </Button>
              </View>
            </Form>
          </View>
        </ScrollView>
      </Popup>
    </View>
  );
}
